//
//  LYPhotoBrowser.m
//  LYPhotoBrowser
//
//  Created by LvYuan on 16/12/12.
//  Copyright © 2016年 LvYuan. All rights reserved.
//

#import "LYPhotoBrowser.h"
#import "UIImageView+WebCache.h"
#import "LYPhotoZoomView.h"
#import "LYPhotoBrowserConfig.h"
#import "LYPhoto.h"

@interface LYPhotoBrowser ()<UIScrollViewDelegate>
{
    BOOL _landScape;
    NSInteger firstIndex;
    LYPhotoZoomView * zoomView;
}
@property (nonatomic, strong)UIScrollView * scrollView;
@property (nonatomic, strong)NSMutableArray * photoViews;
@property (nonatomic, assign)BOOL hasShowedFirst;
@property (nonatomic, strong)UILabel * indexLabel;
@end

static LYPhotoBrowser * browser = nil;

@implementation LYPhotoBrowser

- (instancetype)init{
    self = [super init];
    if (self) {
        _landScape = kShouldLandScape_ly;
    }
    return self;
}

- (NSMutableArray *)photoViews{
    if (_photoViews==nil) {
        _photoViews = [NSMutableArray array];
    }
    return _photoViews;
}

- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
        _scrollView.delegate = self;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator =NO;
        _scrollView.pagingEnabled = YES;
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

- (void)setUp{
    self.view.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = kBackgrounColor_ly;
}

- (void)setCurrentImageIndex:(NSInteger)currentImageIndex{
    _currentImageIndex = currentImageIndex;
    firstIndex = currentImageIndex;
}

/**
 Tool Bar
 */
- (void)setUpToolbars{
    // 1. 序标
    UILabel *indexLabel = [[UILabel alloc] init];
    indexLabel.textAlignment = NSTextAlignmentCenter;
    indexLabel.textColor = [UIColor whiteColor];
    indexLabel.font = [UIFont boldSystemFontOfSize:20];
    indexLabel.backgroundColor = [UIColor colorWithRed:0.1f green:0.1f blue:0.1f alpha:0.3f];
    indexLabel.bounds = CGRectMake(0, 0, 80, 30);
    indexLabel.center = CGPointMake(ScreenWidth_ly * 0.5, 30);
    indexLabel.layer.cornerRadius = 15;
    indexLabel.clipsToBounds = YES;
    if (self.imageCount > 1) {
        indexLabel.text = [NSString stringWithFormat:@"1/%ld", (long)self.imageCount];
        _indexLabel = indexLabel;
        [self.view addSubview:indexLabel];
    }
}


/**
 创建photo试图
 */
- (void)loadZoomViews{

    WEAKSELF_LY;
    for (int i=0; i<self.imageCount; i++) {
        LYPhotoZoomView * zView = [[LYPhotoZoomView alloc]init];
        zView.index = i;
        zView.tapBlock = ^(id sender){
            [wself photoClick:sender];
        };
        [self.scrollView addSubview:zView];
        [self.photoViews addObject:zView];
    }
    [self loadImageAtIndex:self.currentImageIndex];
}


/**
 加载图片

 @param index 相应位置的index
 */
- (void)loadImageAtIndex:(NSInteger)index{
    if (index>_imageCount-1) {
        return;
    }
    LYPhotoZoomView * view = _photoViews[index];
    if (view.loading) {
        return;
    }
    if ([self photoAtIndex:index]){
        view.photo = [self photoAtIndex:index];
    }
    else{
        view.imageView.image = [self placeholderImageAtIndex:index];
    }
    view.loading = YES;
}

/**
 该索引的默认图

 @param index 索引
 @return image
 */
- (UIImage *)placeholderImageAtIndex:(NSInteger)index{
    if (index>_imageCount-1) {
        return nil;
    }
    return [[self photoAtIndex:index] thumbImage];
}

/**
 该索引的photo模型 必须实现这个代理

 @param index 索引
 @return LYPhoto
 */
- (LYPhoto *)photoAtIndex:(NSInteger)index{
    if ([self.delegate respondsToSelector:@selector(photoBrowser:photoAtIndex:)]) {
        return [self.delegate photoBrowser:self photoAtIndex:index];
    }
    return nil;
}

/**
 设置scrollView
 */
- (void)resetScrollView{
    
    CGRect rect = self.view.bounds;
    rect.size.width += kImageViewMargin_ly * 2;
    _scrollView.bounds = rect;
    _scrollView.center = CGPointMake(rect.size.width * 0.5, rect.size.height * 0.5);
    
    CGFloat y = 0;
    __block CGFloat w = _scrollView.frame.size.width - kImageViewMargin_ly * 2;
    CGFloat h = _scrollView.frame.size.height;
    
    [_photoViews enumerateObjectsUsingBlock:^(LYPhotoZoomView *obj, NSUInteger idx, BOOL *stop) {
        CGFloat x =  idx * (kImageViewMargin_ly * 2 + w);
        obj.frame = CGRectMake(x, y, w, h);
    }];
    
    _scrollView.contentSize = CGSizeMake(_photoViews.count * _scrollView.frame.size.width, _scrollView.frame.size.height);
    _scrollView.contentOffset = CGPointMake(self.currentImageIndex * _scrollView.frame.size.width, 0);
    
    
    if (!_hasShowedFirst) {
        [self showFirstImage];
    }
    
    _indexLabel.bounds = CGRectMake(0, 0, 80, 30);
    _indexLabel.center = CGPointMake(rect.size.width * 0.5, 30);
}

/**
 设置首次显示的图片
 */
- (void)showFirstImage{
    
    UIView *sourceView = self.sourceView;
    
    CGRect rect = [sourceView.superview convertRect:sourceView.frame toView:self.view];
    
    UIImageView *tempView = [[UIImageView alloc] init];
    tempView.frame = rect;
    tempView.image = [self placeholderImageAtIndex:self.currentImageIndex];
    [self.view addSubview:tempView];
    tempView.contentMode = UIViewContentModeScaleAspectFit;
    
    
    CGFloat placeImageSizeW = tempView.image.size.width;
    CGFloat placeImageSizeH = tempView.image.size.height;
    CGRect targetTemp;
    
    CGFloat placeHolderH = (placeImageSizeH * ScreenWidth_ly)/placeImageSizeW;
    if (placeHolderH <= ScreenHeight_ly) {
        targetTemp = CGRectMake(0, (ScreenHeight_ly - placeHolderH) * 0.5 , ScreenWidth_ly, placeHolderH);
    } else {//图片高度>屏幕高度
        targetTemp = CGRectMake(0, 0, ScreenWidth_ly, placeHolderH);
    }
    
    //先隐藏scrollview
    _scrollView.hidden = YES;
    _indexLabel.hidden = YES;
    
    [UIView animateWithDuration:kAnimationDuration_ly animations:^{
        //将点击的临时imageview动画放大到和目标imageview一样大
        tempView.frame = targetTemp;
    } completion:^(BOOL finished) {
        //动画完成后，删除临时imageview，让目标imageview显示
        _hasShowedFirst = YES;
        [tempView removeFromSuperview];
        _scrollView.hidden = NO;
        _indexLabel.hidden = NO;
    }];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self resetScrollView];
}


- (void)didMoveToParentViewController:(UIViewController *)parent{
    [self loadZoomViews];
    [self setUpToolbars];
}

#pragma mark - scrollview delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    int index = (scrollView.contentOffset.x + _scrollView.bounds.size.width * 0.5) / _scrollView.bounds.size.width;

    _indexLabel.text = [NSString stringWithFormat:@"%d/%ld", index + 1, (long)self.imageCount];

    long left = index - 1;
    long right = index + 1;
    left = left>0?left : 0;
    right = right>self.imageCount?self.imageCount:right;
    
    for (long i = left; i < right; i++) {
        [self loadImageAtIndex:i];
    }
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    int autualIndex = scrollView.contentOffset.x  / _scrollView.bounds.size.width;
    //设置当前下标
    _currentImageIndex = autualIndex;
    //将不是当前imageview的缩放全部还原 (这个方法有些冗余，后期可以改进)
    for (LYPhotoZoomView *view in _photoViews) {
        if (view.index != autualIndex) {
            view.scrollView.zoomScale = 1.0;
        }
    }
}

#pragma mark - Touch
- (void)handleDoubleTap:(UITapGestureRecognizer *)recognizer{
    
    LYPhotoZoomView *view = (LYPhotoZoomView *)recognizer.view;
    CGPoint touchPoint = [recognizer locationInView:self.view];
    if (view.scrollView.zoomScale <= 1.0) {
        
        CGFloat scaleX = touchPoint.x + view.scrollView.contentOffset.x;//需要放大的图片的X点
        CGFloat sacleY = touchPoint.y + view.scrollView.contentOffset.y;//需要放大的图片的Y点
        [view.scrollView zoomToRect:CGRectMake(scaleX, sacleY, 10, 10) animated:YES];
        
    } else {
        [view.scrollView setZoomScale:1.0 animated:YES]; //还原
    }
    
}

- (void)photoClick:(UITapGestureRecognizer *)recognizer{
    
    LYPhotoZoomView *currentView = _photoViews[self.currentImageIndex];
    [currentView.scrollView setZoomScale:1.0 animated:YES];//还原
    _indexLabel.hidden = YES;

    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    //CGRect screenBounds = [UIScreen mainScreen].bounds;
    if (UIDeviceOrientationIsLandscape(orientation)) {
        [UIView animateWithDuration:0.3f delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            [[UIApplication sharedApplication] setStatusBarOrientation:(UIInterfaceOrientation)UIDeviceOrientationPortrait];
            self.view.transform = CGAffineTransformIdentity;
            self.view.bounds = CGRectMake(0, 0, ScreenWidth_ly, ScreenHeight_ly);
            [self.view setNeedsLayout];
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            [self hidePhotoBrowser:recognizer];
        }];
    } else {
        [self hidePhotoBrowser:recognizer];
    }
}

- (void)hidePhotoBrowser:(UITapGestureRecognizer *)recognizer{
    
    zoomView = (LYPhotoZoomView *)recognizer.view;
    [self dismiss];
}

#pragma mark - life
- (void)dealloc{
    NSLog(@"%s dealloc",__func__);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)loadView{
    [super loadView];
    [self setUp];
}

/**
 show
 */
- (void)show{
    [self showAnimation:YES];
}

- (void)showAnimation:(BOOL)animation{
    UIViewController * controller = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (controller.presentedViewController != nil) {
        controller = controller.presentedViewController;
    }
    [self showInViewController:controller animated:animation];
}

- (void)showInViewController:(UIViewController *)controller animated:(BOOL)animated{
    if (browser != nil) {
        [browser g_removeFromParentViewControllerCallingAppearanceMethods:YES];
    }
    browser = self;
    
    [self g_addToParentViewController:controller callingAppearanceMethods:YES];
    
    self.view.frame = self.view.bounds;
    
}

/**
 dismiss
 */
- (void)dismiss{
    [self dismissAnimation:YES];
}


- (void)dismissAnimation:(BOOL)animation{
    
    UIImageView *currentImageView = zoomView.imageView;
    
    NSUInteger currentIndex = zoomView.index;
    
    if (currentIndex!=firstIndex) {
        
        [UIView animateWithDuration:kHideImageAnimationDuration_ly animations:^{
            self.view.alpha = 0;
        } completion:^(BOOL finished) {
            [self g_removeFromParentViewControllerCallingAppearanceMethods:YES];
        }];
        
    }else{
        
        UIView *sourceView = self.sourceView;
        CGRect targetTemp = [sourceView.superview convertRect:sourceView.frame toView:self.view];
        
        UIImageView *tempImageView = [[UIImageView alloc] init];
        tempImageView.image = currentImageView.image;
        CGFloat tempImageSizeH = tempImageView.image.size.height;
        CGFloat tempImageSizeW = tempImageView.image.size.width;
        CGFloat tempImageViewH = (tempImageSizeH * ScreenWidth_ly)/tempImageSizeW;
        
        if (tempImageViewH < ScreenHeight_ly) {//图片高度<屏幕高度
            tempImageView.frame = CGRectMake(0, (ScreenHeight_ly - tempImageViewH)*0.5, ScreenWidth_ly, tempImageViewH);
        } else {
            tempImageView.frame = CGRectMake(0, 0, ScreenWidth_ly, tempImageViewH);
        }
        [self.view addSubview:tempImageView];
        
        _indexLabel.hidden = YES;
        _scrollView.hidden = YES;
        self.view.backgroundColor = [UIColor clearColor];
        
        [UIView animateWithDuration:kHideImageAnimationDuration_ly animations:^{
            tempImageView.frame = targetTemp;
        } completion:^(BOOL finished) {
            [tempImageView removeFromSuperview];
            [self g_removeFromParentViewControllerCallingAppearanceMethods:YES];
        }];
        
    }
    
}

/**
 MARK: - controller 只能存在一个
 */
- (void)g_addToParentViewController:(UIViewController *)parentViewController callingAppearanceMethods:(BOOL)callAppearanceMethods{
    if (self.parentViewController != nil) {
        [self g_removeFromParentViewControllerCallingAppearanceMethods:callAppearanceMethods];
    }
    
    if (callAppearanceMethods) [self beginAppearanceTransition:YES animated:NO];
    [parentViewController addChildViewController:self];
    [parentViewController.view addSubview:self.view];
    [self didMoveToParentViewController:self];
    if (callAppearanceMethods) {
        [self endAppearanceTransition];
    }
}

- (void)g_removeFromParentViewControllerCallingAppearanceMethods:(BOOL)callAppearanceMethods{
    if (callAppearanceMethods) [self beginAppearanceTransition:NO animated:NO];
    [self willMoveToParentViewController:nil];
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
    if (callAppearanceMethods) {
        [self endAppearanceTransition];
    }
}

/**
 横竖屏
 */
- (BOOL)shouldAutorotate{
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskAll;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
